package model

import (
	"log"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var DB = Init()

func Init() *gorm.DB {
	dsn := "root:@tcp(127.0.0.1:3306)/gin_oj?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Panic("database connect error: ", err)
	}

	tables := []interface{}{
		&CategoryBasic{},
		&ProblemBasic{},
		&ProblemCategory{},
		&UserBasic{},
		&SubmitBasic{},
	}

	for _, table := range tables {
		if !db.Migrator().HasTable(table) {
			if err := db.Migrator().CreateTable(table); err != nil {
				log.Printf("create table failed: %v", err)
			}
		}
	}
	return db
}
